package com.spring_book.spring_book.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
//import com.spring.captchademo.model.CaptchaProperties;
import com.spring_book.spring_book.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@Slf4j
@RequestMapping("/captcha")
@RestController
public class CaptchaController {
//    private static Logger logger = LoggerFactory.getLogger(CaptchaController.class);
    @Autowired
    private CaptchaProperties captchaProperties;
    private static long VALID_Time_OUT = 60*1000;


    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpSession session,HttpServletResponse response) throws IOException {
        //生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(captchaProperties.getWidth(), captchaProperties.getHeight());
        //打印验证码
        String str = lineCaptcha.getCode();
        System.out.println("system生成验证码"+str);
        log.info("logger生成验证码"+str);
        session.setAttribute(captchaProperties.getSession().getKey(),str);
        session.setAttribute(captchaProperties.getSession().getDate(),new Date());
        System.out.println(lineCaptcha.getCode());
        //把验证码写到浏览器
        lineCaptcha.write(response.getOutputStream());
        response.setContentType("image/jpeg");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Pragma", "No-cache");
    }
@RequestMapping("/check")
    public boolean check(String captcha,HttpSession session){
        System.out.println("用户输入验证码:  "+captcha);
        if(!StringUtils.hasLength(captcha)){
            return false;
        }
        String code = (String) session.getAttribute(captchaProperties.getSession().getKey());
        Date date = (Date) session.getAttribute(captchaProperties.getSession().getDate());
        if(date==null || (System.currentTimeMillis()-date.getTime())>VALID_Time_OUT){
            return false;
        }
        return captcha.equalsIgnoreCase(code);
    }
}
